package base.thread_demo.demo08_08;

/**
 * 单利模式:instance = new Singleton();
 * 存在指令重排问题,可能某些线程拿到的instance是个对象,但是对象里面属性没值
 *
 * 后期思考下如何验证上面的问题
 */
public class SingletonDemo {
    static Singleton s1;
    static Singleton s2;
    public static void main(String[] args) throws InterruptedException {
        new Thread(()->{
            s1 = Singleton.getInstance();
        }).start();

        new Thread(()->{
            s2 = Singleton.getInstance();
        }).start();

        Thread.sleep(2000);
        System.out.println(s1 == s2);
    }

}

class Singleton {
    private static Singleton instance;
    private Singleton (){}

    public static Singleton getInstance(){
        if(instance == null){
            synchronized (Singleton.class){
                if(instance == null){
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }

}
